package com.service.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.service.common.Result;
import com.service.order.Order;
import com.service.order.feign.ProductFeignClient;
import com.service.order.sentinel.SentinelFallBack;
import com.service.order.service.OrderService;
import com.service.product.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * 创建订单
     * @return
     */
    @SentinelResource(value = "createOrderMethod",
            blockHandler = "createOrderFallBack",
            blockHandlerClass = SentinelFallBack.class
            )//创建一个sentinel的资源名
    @Override
    public Order createOrder() {
        Order order = new Order();
        order.setId(10L);
        order.setTotalAmount(BigDecimal.ONE);
        order.setUserId(null);
        order.setNickName("罗莱德");
        order.setAddress("北京小米");
        Product productFeign = productFeignClient.createProductFeign();
        order.setProductList(Arrays.asList(productFeign));
        //手动超时
//        try {
//            TimeUnit.SECONDS.sleep(2);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        return order;
    }

    public Order createOrderFallBack(BlockException e){
        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(0L);
        order.setNickName("");
        order.setAddress("异常："+e.getClass());
        return order;
    }
    }
